package com.zcj.demo.utils.response;

import org.springframework.data.domain.Page;

import java.util.*;

/**
 * @author 68300119
 */
public final class ResponseBuilder<T> {

	private List<?> list = null;

	private long total;

	private int pageSize;

	private int currentPage;

	private final Map<String, Object> parameters = new HashMap<>();

	public ResponseBuilder() {

	}

	public ResponseBuilder<T> with(final String key, final Object value) {
		parameters.put(key, value);
		return this;
	}

	public ResponseBuilder<T> withPage(Page<T> page) {
		if (null != page) {
			this.total = page.getTotalElements();
			this.pageSize = page.getSize();
			this.currentPage = page.getNumber();
			this.list = Collections.unmodifiableList(page.getContent());
		}
		return this;
	}

	public ResponseBuilder<T> withList(List<T> list) {
		this.list = Collections.unmodifiableList(list);
		return this;
	}

	public ResponseBuilder<T> withTotal(long total) {
		this.total = total;
		return this;
	}

	public ResponseBuilder<T> withPageSize(int pageSize) {
		this.pageSize = pageSize;
		return this;
	}

	public ResponseBuilder<T> withPageSize(int currentPage, int pageSize) {
		this.currentPage = currentPage;
		this.pageSize = pageSize;
		return this;
	}

	public AbstractResponse build() {
		return new DefaultResponse(this.list, this.total, this.pageSize, this.currentPage,
				parameters.size() > 0 ? new LinkedHashMap<>(parameters) : null);
	}

}
